package com.icehand.payment.pay.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.icehand.common.code.PaymentCode;
import com.icehand.common.constants.CommonConstants;
import com.icehand.common.enums.PayChannelEnum;
import com.icehand.mybatis.payment.mapper.PayNotifyRecordMapper;
import com.icehand.payment.model.NotifyWrapper;
import com.icehand.payment.model.PayWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;

/**
 * @author icehand
 */
@Slf4j
public class AliAppPay extends BaseAliPay {
    private static final PayChannelEnum CHANNEL = PayChannelEnum.ALI_APP_PAY;

    public AliAppPay(RestTemplate restTemplate, PayNotifyRecordMapper payNotifyRecordMapper) {
        super(restTemplate, payNotifyRecordMapper);
    }

    @Override
    public void pay(PayWrapper payWrapper) {
        if(!payWrapper.getPayChannelEnum().equals(CHANNEL)){
            return;
        }

        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        request.setNotifyUrl(payWrapper.getConfig().getString(CommonConstants.K_NOTIFY_URL));
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setOutTradeNo(payWrapper.getBaseOrder().getOrderNo());
        model.setBody(payWrapper.getBaseOrder().getBody());
        model.setTotalAmount(payWrapper.getBaseOrder().getAmount().setScale(2, BigDecimal.ROUND_UP).toPlainString());
        model.setSubject(payWrapper.getBaseOrder().getSubject());
        model.setBody(payWrapper.getBaseOrder().getBody());
        model.setProductCode("QUICK_MSECURITY_PAY");

        //timeout express
        long diff = payWrapper.getBaseOrder().getExpireTime().getTime() - System.currentTimeMillis();
        model.setTimeoutExpress(diff / (1000 * 60) + "m");
        request.setBizModel(model);

        AlipayTradeAppPayResponse response;
        try {
            response = createAlipayClient(payWrapper).sdkExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            payWrapper.getBizResult().error(PaymentCode.PAY_FAIL);
            return;
        }

        payWrapper.putData(response.getBody());
    }

    @Override
    public void payNotify(NotifyWrapper notifyWrapper) {

    }

    @Override
    public PayChannelEnum getChannel() {
        return CHANNEL;
    }
}
